
/***************************************************************************
 *   Copyright (C) 2008 by Dr Pierre-Marie DESOMBRE   *
 *   pm.desombre@medsyn.fr   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "string.h"
#include "math.h"
#include "lecturedialog.h"
#include "modifierdialog.h"
#include "lectlabel.h"
#include "parametre.h"
#include "connexion.h"
#include "constants.h"
#include "icore.h"
#include "settings.h"


static inline Common::Settings *settings(){return Common::ICore::instance()->settings();}
extern QString g_pathabsolu;
extern int g_increment;
using namespace Common;
using namespace Constants;
Lecturalarme::Lecturalarme(QWidget *parent)
:QWidget(parent)
{
  setupUi(this);
  m_dbAlarmes = QSqlDatabase::database(DB_ALARMES);
  m_dbDrTux = QSqlDatabase::database(DB_DRTUX);
  int timing                             = 100000;
  QString textelabel                     = "Lecture des alarmes avant le "+QDateTime::currentDateTime().toString("dd.MM.yyyy hh:mm:ss")+". "
                                           "Pour lire tout c'est le bouton <i>Voir toutes<i/>";
  std::string textelabelstring           = textelabel.toStdString();
  const char *textelabelchar             = textelabelstring.c_str();
  label                                 -> setText(textelabelchar);
  setAttribute(Qt::WA_DeleteOnClose);
  m_modele                               = new QSqlTableModel(this,m_dbAlarmes);
  afficher();
  m_x = m_modele                         -> rowCount();
  timing = settings()->value(S_TIMING).toInt();
  connect(pushButton,  SIGNAL(clicked()),this,SLOT(voir_et_changer()));
  connect(pushButton_2,SIGNAL(clicked()),this,SLOT(voir_et_changer()));
  connect(pushButton_3,SIGNAL(clicked()),this,SLOT(effacer()));
  connect(pushButton_4,SIGNAL(clicked()),this,SLOT(fermer()));
  connect(pushButton_5,SIGNAL(clicked()),this,SLOT(enregistrer()));
  connect(pushButton_6,SIGNAL(clicked()),this,SLOT(parametrer()));

  m_timer                                 = new QTimer(this);
  m_timer                                -> setInterval(timing);
  connect(m_timer,SIGNAL(timeout()),this,SLOT(labelalerte()));
  m_timer                                -> start();
  //this->installEventFilter();
}

Lecturalarme::~Lecturalarme(){
    delete m_modele;
    delete m_timer;
    m_x = 0;
    }
void Lecturalarme::voir_et_changer()
{
  modifierdialog *modif = new modifierdialog(this);
  modif->show();
  /*if(modif->exec() == QDialog::Accepted)
  {
  modif->modifierdialog::effacer(modif);
  }*/
}

void Lecturalarme::effacer()
{
  QString id;
  QModelIndex index                     = tableView->QAbstractItemView::currentIndex();
  int i                                 = index.row();
  // id = c_ident[i];
  //QSqlQuery query;
  //query.exec("DELETE FROM alarmes WHERE Alarm_IDDos = '"+id+"'");
  m_modele                             -> removeRows(i,1,QModelIndex());
 /* if((m_modele -> submitAll())== false){
      QMessageBox::warning(0,tr("erreur"),trUtf8("Problème d'enregistrement 97 dans la base alarmes."),QMessageBox::Ok);
      }*/
}


void Lecturalarme::enregistrer()
{
  QString alarmeId                 = "";
  QString textealarme              = "";
  int alarmvalid                   = 0;
  QString utilisateur              = "";
  QString medintuxVersion = settings()->value(S_MEDINTUX_VERSION).toString();
  QSqlQuery query(m_dbAlarmes);
  if((query.exec("SELECT Alarm_IDDos,TextAlarme,Alarm_valid,Alarm_utilisateur FROM alarmes "
                 "WHERE Alarm_Date <= '"+QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")+"'"))==false){
      QMessageBox::warning(0,tr("erreur"),trUtf8("Problème de connexion à la base alarmes."),QMessageBox::Ok);
      }
  else{
      while(query.next())
     {
         alarmvalid = query.value(2).toInt();
         bool b = (alarmvalid==1);
             if(b == false)
             {
                 alarmeId             = query.value(0).toString();
                 utilisateur          = query.value(3).toString();
                 textealarme          = query.value(1).toString();
                 textealarme           .replace(QRegExp("\\n"),"<br/>");
                 QString deuxpoints   = " : ";
                 textealarme = "<html><head><meta name=\"qrichtext\" content=\"1\" /></head>"
                               "<body style=\"font-size:9pt;font-family:Courier\"><p>"
                               "<span style=\"font-size:16pt;text-decoration:underline;color:#0000ff\">"
                               ""+textealarme+"</span>"+deuxpoints+"</p></body></html>";

                 QSqlQuery query2(m_dbDrTux);
                 if(!query2.exec("INSERT INTO RubriquesBlobs (RbDate_PrimKey,RbDate_DataRub,RbDate_IDDos) "
                             "VALUES (NULL,'"+textealarme+"','"+alarmeId+"')")){
                             qWarning() << __FILE__ << QString::number(__LINE__) << query2.lastError().text() ;
                             }
                 QString lastid = query2.lastInsertId().toString();

                 QSqlQuery query3(m_dbDrTux);
             if(medintuxVersion == "12"){
                 if(!query3.exec("INSERT INTO RubriquesHead"
                             "(RbDate_PrimKey,RbDate_IDDos,RbDate_TypeRub,RbDate_NomDate,RbDate_SubTypeRub,"
                             "RbDate_Date,RbDate_CreateUser,RbDate_CreateSignUser,RbDate_Duree,"
                             "RbDate_Ref_NumDoss,RbDate_RefBlobs_Primkey)"
                             "VALUES (NULL,'"+alarmeId+"',20030000,'Alarme',"
                             "NULL,'"+QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")+"',"
                             "'"+utilisateur+"','"+utilisateur+"',0,0,'"+lastid+"')")){
                             qWarning() << __FILE__ << QString::number(__LINE__) << query3.lastError().text() ;
                             }
                         }
             else if(medintuxVersion == "14"){
                  if(!query3.exec("INSERT INTO RubriquesHead"
                             "(RbDate_PrimKey,"
                             "RbDate_IDDos,"
                             "RbDate_TypeRub,"
                             "RbDate_NomDate,"
                             "RbDate_SubTypeRub,"
                             "RbDate_Date,"
                             "RbDate_CreateUser,"
                             "RbDate_CreateSignUser,"
                             "RbDate_Fin,"
                             "RbDate_DureeMod,"
                             "RbDate_Prop_0,"
                             "RbDate_Prop_1,"
                             "RbDate_Prop_2,"
                             "RbDate_Prop_3,"
                             "RbDate_Prop_4,"
                             "RbDate_Ref_NumDoss,"
                             "RbDate_RefBlobs_PrimKey)"
                             "VALUES (NULL,'"+alarmeId+"',20030000,'Alarme',"
                             "NULL,'"+QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")+"',"
                             "'"+utilisateur+"','"+utilisateur+"',"
                             "NULL,"
                             "-1,"
                             "0,0,0,0,0,1,"
                             "'"+lastid+"')")){
                             qWarning() << __FILE__ << QString::number(__LINE__) << query3.lastError().text() ;
                             }
                         }
                  

                 QSqlQuery query4(m_dbAlarmes);
                 if(!query4.exec("UPDATE alarmes SET Alarm_valid = '1' WHERE Alarm_IDDos = '"+alarmeId+"'")){
                     qWarning() << __FILE__ << QString::number(__LINE__) << query4.lastError().text() ;
                     }

             }//if
       }//while

  }//else
  this->showMinimized();
}

void Lecturalarme::fermer(){
  emit QApplication::closeAllWindows();
}

void Lecturalarme::labelalerte()
{
  QSqlTableModel *modele2         = new QSqlTableModel(this,m_dbAlarmes);
  modele2                         ->setTable ("alarmes");
  modele2                         ->setFilter("Alarm_Date <= '"+QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")+"'");
  modele2                         ->select();
  m_y                             = modele2->rowCount();
//////////////////////////déclenchement du widget d'alerte/////////////////////////////////
  if(m_y-m_x!=0){//si rajout d'une rangée depuis que le constructeur est lancé

      int z                       = m_y-1;
      QModelIndex indexnom        = modele2->index(z,4,QModelIndex());
      QModelIndex indexprenom     = modele2->index(z,5,QModelIndex());
      QModelIndex indexcause      = modele2->index(z,1,QModelIndex());
      QModelIndex indexValide     = modele2->index(z,7,QModelIndex());
      QString nom                 ="";
      QString prenom              ="";
      QString cause               = "";
      QString nomprenomcause      = "";//récupération du nom, du prénom et de la cause de l'alerte.
      int     Valide              = 0;
      nom                         = modele2->data(indexnom,Qt::DisplayRole).toString();
      prenom                      = modele2->data(indexprenom,Qt::DisplayRole).toString();
      cause                       = modele2->data(indexcause,Qt::DisplayRole).toString();
      nomprenomcause              = nom+","+prenom+"<br>pour "+cause;
      Valide                      = modele2->data(indexValide,Qt::DisplayRole).toInt();
      qDebug() << "valide ="+QString::number(Valide);
////////////////////////////on lance le popup avec son argument.
  m_labelclic                     = new mylabel(nomprenomcause);
      if((Valide == 1) == false){
          m_labelclic            -> show();

          if((this->isMinimized())== false){
              m_modele          -> clear();
              afficher();
              }
      }

  m_x++;//on incrémente pour ne pas relancer le widget pour la  même alerte.
  g_increment++;//pour taille fenêtre
  //delete m_labelclic;

  }
}

void Lecturalarme::lanceslot(){//ne sert à rien
  this->showMaximized();
}

bool Lecturalarme::event(QEvent *event){
  if(event->type() == QEvent::WindowStateChange){
      if(this->windowState() == Qt::WindowMinimized){
        /*QLabel *label = new QLabel;
        label ->setText("essai this->windowState() == Qt::WindowMinimized");
        label->show();*/
            //m_modele               -> clear();
      afficher();
      }
  //tableView->show();
  }
  //event                         -> accept();
  return QWidget::event(event);
}

void Lecturalarme::afficher(){

  m_modele               -> setTable("alarmes");
  m_modele               -> setFilter("Alarm_Date <= '"+QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")+"'");
    if(!m_modele->select()){
      QMessageBox::warning(0,tr("attention!"),trUtf8("la table alarmes n'est pas installée ou son nom dans la base est faux."
              "\nVeuillez lancer pensebetux dans l'observation\nqui vous guidera pas à pas"),QMessageBox::Warning,QMessageBox::Ok);
  }
  tableView              -> setModel(m_modele);
  tableView              -> setSelectionBehavior(QAbstractItemView::SelectRows);
  tableView              -> setSelectionMode(QAbstractItemView::SingleSelection);
  tableView              -> setColumnHidden(0,true);
  tableView              -> setColumnHidden(3,true);
  tableView              -> setColumnHidden(6,true);
  tableView              -> horizontalHeader()->setResizeMode(QHeaderView::Stretch);
  tableView              -> verticalHeader()  ->setResizeMode(QHeaderView::Stretch);
  tableView              -> show();
}


void Lecturalarme::parametrer(){
  parametre *param       =  new parametre(this);
             param       -> show();

}






